<template>
    <div class="container">
        <!-- 顶部搜索栏与按钮区域 -->
        <el-row :gutter="20" class="header">
            <el-col :span="12" :offset="6" class="header-col">
                <input type="text" v-model="searchText" placeholder="请输入内容搜索" class="search-input" />
                <el-select v-model="types" placeholder="请选择搜索添加" style="width: 150px; margin-left: 10px;">
                    <el-option label="菜谱名字" value="cookbName" />
                    <el-option label="菜系" value="cuisine" />
                    <el-option label="地方" value="place" />
                </el-select>
                <el-button type="primary" size="default" @click="searchBtn" style="margin-left: 15px;">搜索</el-button>
                <el-button type="primary" size="default" @click="addBtn">添加</el-button>
            </el-col>
        </el-row>

        <!-- 内容区域 -->
        <!-- 对每个 foodTableList 中的项目使用 el-row 作为容器 -->
        <el-card style="height: auto;width: auto;">
            <el-row :gutter="20" v-for="(food, index) in foodTableList" :key="index" class="content">
                <el-col :span="3" :offset="6" class="img-col">
                    <img class="img" :src="generateImageUrl(food.recipeImg)" alt="菜品图片" />
                </el-col>
                <el-col :span="9" class="neirong-col">
                    <h3 class="h3">{{ food.cookbName }}</h3>
                    <p class="p">{{ food.content }}</p>
                    <div class="anniu">
                        
                        <el-button type="info" :icon="Pointer" circle @click="likeBtn(food.cookbId)">{{ likeCountMap[food.cookbId] || 0 }}</el-button>
                        <el-button type="warning" :icon="Star" circle style="margin-right: 8px;"
                            @click="handleFavoriteClick(food)"></el-button>
                        <el-button type="info" :icon="Message" circle style="margin-right: 8px;" @click="commentBtn(food)"></el-button>
                    </div>
                </el-col>
            </el-row>
        </el-card>

    </div>
    <Dialog :title="dialog.title" :width="dialog.width" :height="dialog.height" :visible="dialog.visible"
        @on-close="onClose" @on-confirm="commit">

        <el-form :model="addfoodform" ref="addFormRef" :rules="rule">
            <!-- 菜谱名字 -->
            <el-form-item label="菜谱名字" prop="cookbName">
                <el-input v-model="addfoodform.cookbName" placeholder="请输入菜谱名称" />
            </el-form-item>

            <!-- 菜系 -->
            <el-form-item label="菜系" prop="cuisine">
                <el-select v-model="addfoodform.cuisine" placeholder="请选择所属菜系" clearable>
                    <el-option v-for="item in cuisineOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>

            <!-- 地方 -->
            <el-form-item label="地方" prop="place">
                <el-input v-model="addfoodform.place" placeholder="请输入所处地区" />
            </el-form-item>

            <!-- 做法内容 -->
            <el-form-item label="做法内容" prop="content">
                <el-input v-model="addfoodform.content" placeholder="请输入详细做法内容" />
            </el-form-item>

            <UploadImg ref="imageUploader"></UploadImg>

        </el-form>

    </Dialog>

</template>
<script setup lang="ts">
import { Check, Delete, Edit, Message, Search, Star,Pointer   } from '@element-plus/icons-vue'
import { onMounted, reactive, ref } from 'vue';
import { StatusType, type FoodTable } from '@/api/food/foodTable'
import { addRecipeApi, getRecipeApi } from '@/api/food';
import { ElMessage, type FormInstance } from 'element-plus';
import Dialog from '@/components/dialog/Dialog.vue';
import useDialog from '@/hooks/usedialog';
import UploadImg from '@/components/upload/UploadImg.vue';
import { useImageUrlStore } from '@/store/imgUrl';
import { useUserStore } from '@/store/islogin/index'
import { useFoodStore } from '@/store/comment/index'
import router from '@/router';
import { addFavoriteApi } from '@/api/Favorite';
import http from '@/http';
const types = ref('')
//获取图片store
const userUrlStore = useImageUrlStore()
//获取用户信息store
const useUser = useUserStore()
//获取菜谱信息store
const useFood = useFoodStore()
//获取form表单组件实例
const addFormRef = ref<FormInstance>();
//搜索框参数
const searchText = ref('')
//搜索参数
const keyword = reactive<FoodTable>({
    cookbId: '',
    userId: '',
    adminId: '',
    cookbName: '',
    cuisine: '',
    place: '',
    content: '',
    recipeImg: '',
    createTime: '',
    updateTime: '',
    status: StatusType.Prohibit,
    reviewedTime: '',
    commentCount: 0,
    favoriteCount: 0
})
//内容接受数组
const foodTableList = reactive<FoodTable[]>([])
// 点击搜索按钮
const searchBtn = () => {
    if (types.value == 'cookbName') {
        keyword.cookbName = searchText.value
        keyword.cuisine = ''
        keyword.place = ''
    }
    if (types.value == 'cuisine') {
        keyword.cuisine = searchText.value
        keyword.place = ''
        keyword.cookbName = ''
    }
    if (types.value == 'place') {
        keyword.place = searchText.value
        keyword.cookbName = ''
        keyword.cuisine = ''
    }
    getList()
    console.log(keyword)
}
//菜系列表
const cuisineOptions = reactive([
  { value: '川菜', label: '川菜' },
  { value: '湘菜', label: '湘菜' },
  { value: '粤菜', label: '粤菜' },
  { value: '闽菜', label: '闽菜' },
  { value: '苏菜', label: '苏菜' },
  { value: '浙菜', label: '浙菜' },
  { value: '徽菜', label: '徽菜' },
  { value: '鲁菜', label: '鲁菜' },

  { value: '楚菜', label: '楚菜' },
  { value: '京菜', label: '京菜' },
  { value: '豫菜', label: '豫菜' },
  { value: '陕菜', label: '陕菜' },

  { value: '东北菜', label: '东北菜' },
  { value: '本帮菜', label: '本帮菜' },
  { value: '潮州菜', label: '潮州菜' },
  { value: '客家菜', label: '客家菜' },
  { value: '云南菜', label: '云南菜' },
  { value: '贵州菜', label: '贵州菜' },
  { value: '新疆菜', label: '新疆菜' },
  { value: '清真菜', label: '清真菜' },

  { value: '家常菜', label: '家常菜' },
  { value: '其他', label: '其他' }
]);
//添加菜谱列表参数
const addfoodform = reactive({
    cookbId: '',
    userId: '',
    adminId: '',
    cookbName: '',
    cuisine: '',
    place: '',
    content: '',
    recipeImg: '',
    createTime: '',
    updateTime: '',
    status: StatusType.Prohibit,
    reviewedTime: '',
    commentCount: 0,
    favoriteCount: 0
})
//收藏菜谱参数
const addFavoriteForm = reactive({
    favoriteId: '',
    userId: '',
    cookbId: '',
    createdTime: ''
})
// 点击添加按钮
const addBtn = () => {
    dialog.visible = true
    dialog.title = '添加菜谱'
    dialog.height = 800
}

const getList = async () => {
    const res = await getRecipeApi(keyword)
    if (res.code === 200) {
        ElMessage.success('运行成功')
        foodTableList.splice(0, foodTableList.length, ...res.data);
    }
}
//图片动态刷新
// 全局缓存版本号（核心控制变量）
const cacheVersion = ref(Date.now())
// 生成带缓存控制的图片URL
const generateImageUrl = (imageUrl: string | string[]) => {
    if (!imageUrl) return ''
    // 智能拼接参数：已有参数则加&，否则加?
    const separator = imageUrl.includes('?') ? '&' : '?'
    return `${imageUrl}${separator}v=${cacheVersion.value}`
}
interface likeTable {
    likeId: string,
    userId: string,
    cookbId: string, 
    createdAt: string
}
const like = reactive<likeTable>({
    likeId: '',
    userId: '',
    cookbId: '',
    createdAt: ''
})
// 存储点赞数的响应式对象
const likeCountMap = ref<Record<string, number>>({});
const addLikeApi = (parm: likeTable) => {
    return http.post("/api/like/add", parm)
}
const getLikeApi = (parm: likeTable) => {
    return http.post("/api/like/get", parm)
}
// 获取对应菜谱的点赞数
const getLikeCount =async ()=>{
  try {
    for (const food of foodTableList) {
      const cookbId = food.cookbId;
      like.cookbId=cookbId
      const res = await getLikeApi(like);
      // 存储到响应式对象中
      if (res.code === 200) {
        likeCountMap.value[cookbId] = res.data;
        console.log(likeCountMap.value)
      }
    }
  } catch (error) {
    console.error('获取点赞数失败', error);
  }
}


//菜谱点赞业务
const likeBtn = async(cookbId: string) => {
    like.cookbId=cookbId
    if(useUser.user){
        like.userId=useUser.user.userId
        const res = await addLikeApi(like)
        if(res.code==200){
            ElMessage.success(res.msg)
            like.cookbId=''
            like.userId=''
            getLikeCount()
        }
    }else{
        ElMessage.error("请进行登录")
    }

}


//弹框参数
const { dialog, onClose, onConfirm, onShow } = useDialog()
// 定义表单验证规则对象
const rule = reactive({
    cookbName: [
        { required: true, message: '请输入菜谱名称', trigger: ['blur', 'change'] },
        { min: 3, max: 15, message: '菜谱名称长度应在3到15个字符之间', trigger: ['blur', 'change'] }
    ],
    cuisine: [
        { required: true, message: '请输入所属菜系', trigger: ['blur', 'change'] }
    ],
    place: [
        { required: true, message: '请输入所处地区', trigger: ['blur', 'change'] }
    ],
    content: [
        { required: true, message: '请输入详细做法内容', trigger: ['blur', 'change'] },
        { min: 10, message: '做法内容不能少于10个字符', trigger: ['blur', 'change'] }
    ]
})


//表单提交
const commit = () => {
    //表单验证
    addFormRef.value?.validate(async (valid) => {
        if (valid) {
            if (userUrlStore.getImageUrl) {
                addfoodform.recipeImg = userUrlStore.getImageUrl
                if (useUser.user?.userId) { addfoodform.userId = useUser.user?.userId }
                const res = await addRecipeApi(addfoodform)
                userUrlStore.deleteImageUrl()
                if (res.code == 200) {
                    ElMessage.success("添加成功")
                    userUrlStore.deleteImageUrl()
                    // 提交数据...
                    // 提交成功后清空表单：
                    // 调用 resetFields 时用可选链
                    addFormRef.value?.resetFields()
                    onClose()
                }
            } else {
                ElMessage.error("请添加图片")
                return
            }
        }
    });
}
//评论按钮
const commentBtn = (food: any) => {
    useFood.setSelectedFood(food)
    ElMessage.success(food.cookbId)
    router.push("/comment")
}
//收藏按钮
const handleFavoriteClick = async (food: any) => {
    useFood.setSelectedFood(food)
    if (useUser.user) {
        addFavoriteForm.userId = useUser.user.userId
        addFavoriteForm.cookbId = useFood.getSelectedFood.cookbId
        const res = await addFavoriteApi(addFavoriteForm)
        if (res.code == 200) {
            ElMessage.success(res.msg)
        } else {
            ElMessage.success(res.msg)
        }
    }

}

// 页面加载完成后自动调用 getList 方法
onMounted(async () => {
  await getList();     // 先等待菜品列表加载完成
  await getLikeCount(); // 再获取点赞数
});

</script>

<style scoped>
.header-col {
    border-radius: 4px;
}

.content {
    margin-top: 20px;
    padding: 10px;
}

.img-col {
    border-radius: 4px;
    height: 175px;
    display: flex;
    /* 水平居中 */
    justify-content: center;
    /* 垂直居中 */
    align-items: center;
    /* 防止图片溢出 */
    overflow: hidden;
}

.img {
    /* 图片最大高度不超过容器 */
    max-height: 100%;
    /* 图片最大宽度不超过容器 */
    max-width: 100%;
    /* 按比例缩放，保证图片完整显示，不超出盒子 */
    object-fit: contain;
}

.neirong-col {
    border-radius: 4px;
    height: 175px;
    display: flex;
    flex-direction: column;
    /* 垂直排列 */
    align-items: center;
    /* 所有子元素水平居中 */
    padding-top: 5px;
    position: relative;
}

.h3 {
    margin-top: 10px;
}

.p {
    margin-top: 10px;
    height: 50%;
    overflow: hidden;
    /* 超出隐藏 */
    text-overflow: ellipsis;
    /* 超出部分显示省略号 */
}
</style>